package com.tanhua.server.service;

import com.aliyuncs.utils.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname VideoService
 * @Description TODO 小视频业务层
 * @Date 2021/3/15 15:17
 * @Created by gan
 */
@Slf4j
@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发布小视频
    @CacheEvict(value = "videoList", allEntries = true)
    public void post(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        log.info("****************发布小视频*******************");
        //获取当前登录用户的用户id
        Long userId = UserHolder.getUserId();
        // 上传视频图片，获取对就看url
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        // 获取上传的视频名称
        String videoFileOriginalFilename = videoFile.getOriginalFilename();
        // 截取文件后缀名
        String suffix = videoFileOriginalFilename.substring(videoFileOriginalFilename.lastIndexOf(".")+1);
        // 上传视频到fdfs
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffix, null);
        // 获取视频的完整路径
        String videoUrl = fdfsWebServer.getWebServerUrl()+storePath.getFullPath();
        // 构建Video对象
        Video video = new Video();
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("百鸟朝凤");
        video.setUserId(userId);
        // 调用api保存
        log.info("video::::" + video.toString());
        videoApi.save(video);
    }


    //分页查询小视频列表
    @Cacheable(value = "videoList", key = "#page + '_' +  #pagesize")
    public PageResult<VideoVo> findPage(Long page, Long pagesize) {
        log.info("****************小视频列表查询*******************");
        //1,调用api分页查询数据列表  video
       PageResult result= videoApi.findPage(page,pagesize);
       //2,获取分页列表中的数据
        List<Video> items =(List<Video>) result.getItems();
        //3,循环遍历集合，一个video就是一个vo
        List<VideoVo>list=new ArrayList<>();
        if(items!=null){
            for (Video video : items) {
                //查询发表用户信息
                UserInfo info = userInfoApi.findByUserId(video.getUserId());
                //创建videoVo
                VideoVo vo=new VideoVo();
                BeanUtils.copyProperties(info,vo);
                BeanUtils.copyProperties(video,vo);
                //设置，补全
                vo.setCover(video.getPicUrl());
               vo.setId(video.getId().toHexString());
                if(StringUtils.isNotEmpty(video.getText())){
                    vo.setSignature(video.getText());//签名
                }
                else
                {
                    vo.setSignature("黑马程序员");//签名
                }
                //从redis中获取操作记录，如果存在返回1，不存在返回0
                String key = "video_follow_"+UserHolder.getUserId()+"_"+video.getUserId();
                if(redisTemplate.hasKey(key)) {
                    vo.setHasFocus(1); //TODO 是否关注
                }else{
                    vo.setHasFocus(0); //TODO 是否关注
                }
                vo.setHasLiked(0); //是否点赞
                list.add(vo);
            }
        }
        //4,存入result中
        result.setItems(list);
        //5,构造返回
        return result;
    }


    //关注视频,作者
    public void followUser(long userId) {
        //创建关注对象
        FollowUser followUser= new FollowUser();
        followUser.setFollowUserId(userId);
        followUser.setUserId(UserHolder.getUserId());
        //调用api添加关注
        videoApi.followUser(followUser);
        //存入redis
        String key = "video_follow_" + UserHolder.getUserId()+ "_" + userId;
        redisTemplate.opsForValue().set(key,"1");
    }


    //取消关注
    public void unfollowUser(long userId) {
        //创建关注对象
        FollowUser followUser=new FollowUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(userId);
        //调用api取消关注
        videoApi.unfollowUser(followUser);
        //删除redis中的记录
        String key =  "video_follow_" + UserHolder.getUserId()+ "_" + userId;
        redisTemplate.delete(key);
  }
}
